//
//  UserIdentifyViewController.m
//  jingdongfang
//
//  Created by MTiMac02 on 2017/9/1.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "UserIdentifyViewController.h"
#import "LTPickerView.h"
#import "UserCertificition.h"
#import "CompanyCertificationUploadPhotoViewController.h"
#import "PhoneNumViewController.h"
#import "IGCommonApi.h"
#import "IGBindPhoneApi.h"
#import "IGCaptchaView.h"

#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@interface UserIdentifyViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSString *userName;
    NSString *userNum;
    NSString *phoneNum;
    NSString *idType;
    
    UserCertificition *userCertificition;
    
    NSInteger timer;
    NSString *vertifynum;
    UIButton *verBtn;
}
@property (retain, nonatomic) IBOutlet UILabel *idLabel;
@property (weak, nonatomic) IBOutlet UIButton *perBtn;
@property (weak, nonatomic) IBOutlet UIButton *comBtn;
@end

@implementation UserIdentifyViewController
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=NSLocalizedString(@"Identity authentication", nil);
    self.IdentyTable.backgroundColor=[UIColor c2Color];
    [self setHeaderUI];
}
-(void)setHeaderUI{
    
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 55)];
    UILabel *userLabel=[[UILabel alloc]init];
    userLabel.text=NSLocalizedString(@"Category", nil);
    userLabel.textColor=[UIColor c4Color];
    userLabel.font=[UIFont font16];
    [userLabel sizeToFit];
    userLabel.centerY=headerView.height/2;
    userLabel.x=headerView.x+15;
    [headerView addSubview:userLabel];
    
    UIButton *personBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    _perBtn=personBtn;
    personBtn.size=CGSizeMake(30, 30);
    personBtn.left=userLabel.right+8;
    personBtn.centerY=userLabel.centerY;
    [personBtn setImage:[UIImage imageNamed:@"badge-拷贝-4"] forState: UIControlStateNormal];
    [personBtn setImage:[UIImage imageNamed:@"badge-拷贝-7"] forState:UIControlStateSelected];
    [personBtn addTarget:self action:@selector(personBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [personBtn setSelected:YES];
    [headerView addSubview: personBtn];
    
    UILabel *personLabel=[[UILabel alloc]init];
    personLabel.text=NSLocalizedString(@"Individual", nil);
    personLabel.textColor=[UIColor c4Color];
    personLabel.font=[UIFont font16];
    [personLabel sizeToFit];
    personLabel.centerY=headerView.height/2;
    personLabel.left=personBtn.right+8;
    [headerView addSubview:personLabel];
    
    UIButton *companyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    _comBtn=companyBtn;
    companyBtn.size=CGSizeMake(30, 30);
    companyBtn.left=personLabel.right+8;
    companyBtn.centerY=headerView.height/2;
    [companyBtn setImage:[UIImage imageNamed:@"badge-拷贝-4"] forState: UIControlStateNormal];
    [companyBtn setImage:[UIImage imageNamed:@"badge-拷贝-7"] forState:UIControlStateSelected];
    [companyBtn addTarget:self action:@selector(companyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [companyBtn setSelected:NO];
    [headerView addSubview:companyBtn];
    
    UILabel *companyLabel=[[UILabel alloc]init];
//    companyLabel.text=@"机构";
    companyLabel.text=NSLocalizedString(@"Institution", nil);
    companyLabel.textColor=[UIColor c4Color];
    companyLabel.font=[UIFont font16];
    [companyLabel sizeToFit];
    companyLabel.centerY=headerView.height/2;
    companyLabel.left=companyBtn.right+8;
    [headerView addSubview:companyLabel];
    
    self.IdentyTable.tableHeaderView=headerView;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 100)];
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeCustom];
    submit.backgroundColor = [UIColor c1Color];
    submit.layer.cornerRadius = 20.f;
    submit.layer.masksToBounds = YES;
    submit.frame = CGRectMake(0, 30, GSCALE(300), GSCALE(44));
    submit.titleLabel.font = [UIFont font16];
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [submit setTitle:@"下一步" forState:UIControlStateNormal];
    [submit setTitle:NSLocalizedString(@"Next", nil) forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    submit.centerX=view.width/2;
    [view addSubview:submit];
    self.IdentyTable.tableFooterView = view;
    
}

#pragma mark----UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    } else if(section == 1 && [IGUser getTel].length != 0) {
        return 1;
    }
    return 2;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    CGFloat x = cell.separatorInset.left;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x, 0, GSCALE(cell.width), 50)];
    textView.borderStyle = UITextBorderStyleNone;
    textView.leftViewMode = UITextFieldViewModeAlways;
    textView.rightViewMode=UITextFieldViewModeUnlessEditing;
    textView.font = [UIFont font16];
    textView.textColor=[UIColor c5Color];
    textView.textAlignment=NSTextAlignmentRight;
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [textView addTarget:self action:@selector(textBeainEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textView addTarget:self action:@selector(textEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    textView.tag = indexPath.section*10+indexPath.row;
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x, 0, GSCALE(cell.width), 50)];
            textView.keyboardType=UIKeyboardTypeDefault;
            textView.enabled=NO;
            textView.leftViewMode = UITextFieldViewModeAlways;
            textView.rightViewMode=UITextFieldViewModeAlways;
            UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
//            left.text = @"证件类型";
            left.text = NSLocalizedString(@"ID Category", nil);
            left.font = [UIFont font16];
            [left sizeToFit];
            left.x=textView.x;
            left.y=0;
            textView.leftView = left;
            
            _idLabel = [[UILabel alloc] initWithFrame:CGRectZero];
//            _idLabel.text = @"身份证";
            _idLabel.text = NSLocalizedString(@"ID", nil);
            _idLabel.textColor=[UIColor c4Color];
            _idLabel.textAlignment=NSTextAlignmentRight;
            _idLabel.font = [UIFont font16];
            [_idLabel sizeToFit];
            textView.rightView = _idLabel;
            [cell.contentView addSubview:textView];
            
            UIButton *identyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            identyBtn.frame=CGRectMake(0, 0, 30, 30);
            [identyBtn setImage:[UIImage imageNamed:@"B-17-1"] forState:UIControlStateNormal];
            identyBtn.centerY=cell.centerY;
            identyBtn.left=textView.right;
            [identyBtn addTarget:self action:@selector(identyBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:identyBtn];
            
            
        }else if (indexPath.row==1) {
            textView.text = userName;
            UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
//            left.text = @"证件姓名";
            left.text = NSLocalizedString(@"ID Name", nil);
            left.font = [UIFont font16];
            [left sizeToFit];
            left.width +=20;
            textView.leftView = left;
            
            UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
            right.text = NSLocalizedString(@"ID Name", nil);
            right.textColor=[UIColor c5Color];
            right.textAlignment=NSTextAlignmentRight;
            right.font = [UIFont font16];
            [right sizeToFit];
            right.width += 20;
            textView.rightView = right;
            [cell.contentView addSubview:textView];
        }else if (indexPath.row==2) {
            textView.text = userNum;
            textView.keyboardType=UIKeyboardTypeASCIICapable;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputTextChange:) name:UITextFieldTextDidChangeNotification object:textView];
            UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
            left.text = NSLocalizedString(@"ID Number", nil);
            left.font = [UIFont font16];
            [left sizeToFit];
            left.width +=20;
            textView.leftView = left;
            
            UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
            right.text = NSLocalizedString(@"ID Number", nil);
            right.textColor=[UIColor c5Color];
            right.textAlignment=NSTextAlignmentRight;
            right.font = [UIFont font16];
            [right sizeToFit];
            right.width += 20;
            textView.rightView = right;
            [cell.contentView addSubview:textView];
        }
    }else if (indexPath.section==1) {
        if ([IGUser getTel].length != 0) {
            if (indexPath.row==0) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.textLabel.text=NSLocalizedString(@"Mobile Number", nil);
                cell.textLabel.textColor=[UIColor c4Color];
                cell.textLabel.font=[UIFont font16];
                cell.textLabel.textAlignment=NSTextAlignmentLeft;
                cell.detailTextLabel.textColor=[UIColor c5Color];
                cell.detailTextLabel.font=[UIFont font16];
                cell.detailTextLabel.right=cell.left;
                cell.accessoryType = UITableViewCellAccessoryNone;
                cell.userInteractionEnabled=NO;
                cell.detailTextLabel.text=[IGUser getTel];
            }
        } else {
            if (indexPath.row==0) {
                textView.text = phoneNum;
                textView.keyboardType = UIKeyboardTypePhonePad;
                UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
                left.text=NSLocalizedString(@"Mobile Number", nil);
                left.textColor=[UIColor c4Color];
                left.font = [UIFont font16];
                [left sizeToFit];
                left.width += 20;
                textView.leftView = left;
                
                UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
                right.text = NSLocalizedString(@"Input Mobile Number", nil);
                right.textColor=[UIColor c5Color];
                right.textAlignment=NSTextAlignmentRight;
                right.font = [UIFont font16];
                [right sizeToFit];
                right.width += 20;
                textView.rightView = right;
                [cell.contentView addSubview:textView];
            }else if (indexPath.row==1) {
                textView.size=CGSizeMake(KSCREENWIDTH-2*x-96, 50);
                textView.text = vertifynum;
                textView.keyboardType = UIKeyboardTypePhonePad;
                UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
                left.text = NSLocalizedString(@"Verification Code", nil);
                left.font = [UIFont font16];
                [left sizeToFit];
                left.width +=20;
                textView.leftView = left;
                
                UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
                right.text = NSLocalizedString(@"SMS Code", nil);
                right.textColor=[UIColor c5Color];
                right.textAlignment=NSTextAlignmentRight;
                right.font = [UIFont font16];
                [right sizeToFit];
                right.width += 20;
                textView.rightView = right;
                [cell.contentView addSubview:textView];
                
                UIButton *identyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
                [identyBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal ];
                [identyBtn setTitleColor:[UIColor c5Color] forState:UIControlStateDisabled];
                [identyBtn setTitleColor:[UIColor c1Color] forState:UIControlStateNormal];
                [identyBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
                identyBtn.enabled = YES;
                identyBtn.titleLabel.font=[UIFont font16];
                [identyBtn sizeToFit];
                identyBtn.centerY=textView.centerY;
                identyBtn.x=KSCREENWIDTH-x-identyBtn.width;
                verBtn=identyBtn;
                [cell.contentView addSubview:identyBtn];
                
                UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
                line.backgroundColor = [UIColor c6Color];
                [cell.contentView addSubview:line];
            }
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self identyBtnClick];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.01;
    }
    return 10.f;
}
-(void)inputTextChange:(NSNotification *)obj
{
    if (!userNum || userNum.length == 0) {
        return;
    }
    UITextField *textField = (UITextField *)obj.object;
    NSCharacterSet *nameCharacters = [[NSCharacterSet                                           characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"] invertedSet];
        if (textField.text.length < 1) {
            return;
        }
        //取出最后一位
        NSString *lastStr = [textField.text substringFromIndex:textField.text.length-1];
        NSRange userNameRange = [lastStr rangeOfCharacterFromSet:nameCharacters];
        //最后一位是特殊字符
        if (userNameRange.location != NSNotFound) {
            textField.text = [textField.text substringToIndex:(textField.text.length - 1)];
    }
}
-(void)personBtnClick:(UIButton *)btn{
    btn.selected= !btn.selected;
    if ([self.perBtn isSelected]) {
        [self.comBtn setSelected:NO];
    }else if(![self.perBtn isSelected]){
        [self.comBtn setSelected:YES];
    }
}

-(void)companyBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    if ([_comBtn isSelected]) {
        [_perBtn setSelected:NO];
    }else if(![_comBtn isSelected]){
        [_perBtn setSelected:YES];
    }
}

-(void)nextAction:(UIButton *)btn{
    [self.view endEditing:YES];
    if (userName.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Your Name", nil)];
        return;
    }
    if (userNum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Your ID Number", nil)];

        return;
    }
    
    if ([IGUser getTel].length == 0) {
        if (phoneNum.length==0) {
            [self presentMessageTips:NSLocalizedString(@"Please link your mobile number first.", nil)];

            return;
        }
        if (vertifynum.length==0) {
            [self presentMessageTips:NSLocalizedString(@"Please Input Verification Code", nil)];

            return;
        }
    }
else {
        [self jumpToNextStep];
        return;
    }
    
    IGBindPhoneApi *bindPhoneApi = [IGBindPhoneApi new];
    bindPhoneApi.phone = phoneNum;
    bindPhoneApi.smsCode = vertifynum;
    bindPhoneApi.type = @"0";
    __weak typeof(self) weakSelf = self;
    [bindPhoneApi startWithDecodeClass:[IGBlindResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [IGUser saveTel:phoneNum];
            
            [weakSelf jumpToNextStep];
        }
    }];
}

- (void)jumpToNextStep {
    CompanyCertificationUploadPhotoViewController *compVC = [[UIStoryboard storyboardWithName:@"UserCertification" bundle:nil] instantiateViewControllerWithIdentifier:@"CompanyCertificationUploadPhotoViewController"];
    if ([self.perBtn isSelected]) {
        compVC.userType=NSLocalizedString(@"Institution", nil);
        compVC.type=0;
    }else if ([self.comBtn isSelected]){
        compVC.userType=NSLocalizedString(@"Individual", nil);
        compVC.type=1;
    }
            compVC.userType=NSLocalizedString(@"Institution", nil);
            compVC.certificatType=self.idLabel.text;
            compVC.name=userName;
            compVC.certificateCode=userNum;
            [UIViewController ig_pushViewController:compVC animated:YES];
}

- (void)textBeainEditing:(UITextField *)textView {
    self.IdentyTable.bounces = YES;
    textView.rightViewMode=UITextFieldViewModeNever;
}

- (void)textEndEditing:(UITextField *)textView {
    self.IdentyTable.bounces = NO;
    [self.IdentyTable resignFirstResponder];
    if(textView.text.length!=0){
        textView.rightViewMode=UITextFieldViewModeNever;
    } else{
        textView.rightViewMode=UITextFieldViewModeUnlessEditing;
    }
}
- (void)textChange:(UITextField *)textView {
    //证件类型
    if (textView.tag == 0) {
  
    }//证件姓名
    if (textView.tag == 1) {
        BOOL ishas = [NSString stringContainsEmoji:textView.text];
        if (ishas) {
            [self presentMessageTips:NSLocalizedString(@"Emoji Unavailable", nil)];
            [textView setText:[self disable_emoji:[textView text]]];
            return;
        }
        userName=textView.text;
    }//证件号码
    if (textView.tag == 2) {
        userNum = textView.text;
    }//手机号码
    if (textView.tag == 10) {
        if (textView.text.length>11) {
            textView.text = [textView.text substringToIndex:11];
        }
        phoneNum = textView.text;
    }
    if (textView.tag == 11) {
        vertifynum = textView.text;
    }
}

//禁止输入表情
- (NSString *)disable_emoji:(NSString *)text
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.IdentyTable resignFirstResponder];
}

-(void)identyBtnClick {
    LTPickerView* pickerView = [LTPickerView new];
    pickerView.dataSource = @[NSLocalizedString(@"ID", nil),NSLocalizedString(@"Passport", nil)];//设置要显示的数据
    pickerView.defaultStr = NSLocalizedString(@"ID", nil);//默认选择的数据
    [pickerView show];//显示
    //回调block
    pickerView.block = ^(LTPickerView* obj,NSString* str,int num){
        self.idLabel.text = str;
        [self.idLabel sizeToFit];
    };
}

- (void)getCode{
    [self.view endEditing:YES];
    if (phoneNum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phoneNum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [IGCaptchaView num:phoneNum showCaptcha:^(NSString *cap) {
        [weakSelf getRealCode:cap];
    }];
}

- (void)getRealCode:(NSString *)code {
    if (phoneNum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phoneNum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    [self showText:NSLocalizedString(@"Sending...", nil)];
    timer = 60;
    IGCommonApi *commonApi = [[IGCommonApi alloc] init];
    commonApi.apiType = IGiGalleryApiTypeMemberGetPhoneSMSNew;
    commonApi.phone = phoneNum;
    commonApi.code = code;
    __weak typeof(self) weakSelf = self;
    [commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf presentMessageTips:NSLocalizedString(@"Sent Successfully", nil)];
                verBtn.userInteractionEnabled = NO;
                NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
                [verBtn setTitle:title forState:UIControlStateNormal];
                [verBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerDown:) userInfo:verBtn repeats:YES];
            });
        }
    }];
}

- (void)timerDown:(NSTimer *)time {
    timer--;
    NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
    [verBtn setTitle:title forState:UIControlStateNormal];
    [verBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    if (timer == 0) {
        verBtn.userInteractionEnabled = YES;
        [verBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal];
        [verBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
        [time invalidate];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
